import ts from "typescript";
import HTTP from "node:http"
import {URL} from 'node:url';
import fs from "fs-extra"

import querystring from "querystring"

const i18nSet = new Set<string>;
const kinds = {} as any;
const wushangkinds = {} as any;

const getReg = () => {
    // --------  仅chrome支持 /((?<!\\)["']).*?(?<!\\)\1/g,
    const regstr = "((?<!\\\\)[\"']).*?(?<!\\\\)\\1";
    return new RegExp(regstr, "g");
}
const getZhReg = () => {
    //"[\u4e00-\u9fa5]+"    \$t($0)
    const regstr = "[\u4e00-\u9fa5]+";
    return new RegExp(regstr, "g");
}


export const buildRes = (code: string) => {
    const node = ts.createSourceFile("x.ts", code, 99);
    const getArgs = (node, parent) => {
        node.forEachChild((item) => {
            if (item && item.kind == 10) {
                const text = item.text;
                const k = parent.kind;
                if (node.kind != 204 && node.kind != 296 && node.kind != 221 && node.kind != 79 && node.kind != 222 && node.kind != 207) { //如果不是是数组中的参数
                    if (!/[\u4e00-\u9fa5]+/.test(text)) {
                        if (node.expression.text == "$t") {
                            i18nSet.add(text);
                        } else {
                            wushangkinds[text] = node.kind;
                        }
                    } else {
                        if ("ID：" != text) {
                            i18nSet.add(text);
                        }
                    }
                }
            }
            getArgs(item, node);
        });
    }
    const forItems = (node, parent, grandpa) => {
        node.forEachChild((item) => {
            if (item && item.kind == 79 && item.text == "$t") {//如果是方法调用名称是$t,则找其对应该方法的参数
                getArgs(grandpa, grandpa);
            }
            forItems(item, node, parent);
        });
    }
    forItems(node, node, node);
};

const writeFile = (filePath: string, code: string) => {
    fs.outputFile(filePath, code, "utf-8");
}
const httpRequestPromise = (options) => {
    return new Promise((resolve, reject) => {
        const POST_DATA = options.data;
        const urls = new URL(options.url);
        const params = [] as string[];
        for (const p in POST_DATA) {
            params.push(p + "=" + POST_DATA[p]);
        }
        const paramsStr = querystring.stringify(POST_DATA);
        const POST_OPTIONS = {
            host: urls.hostname,
            port: urls.port,
            path: urls.pathname + "/" + options.path,
            method: 'POST',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                "Content-Length": paramsStr.length,
            }
        };

// 接受返回的数据
        function requestOnResponse(incomingMessage) {
            const data = []
            incomingMessage.on('data', chunk => {
                data.push(...chunk)
            })

            incomingMessage.on('end', () => {
                const _date = JSON.parse(new TextDecoder().decode(new Uint8Array(data)))
                resolve(_date)
                // if (options.success) {
                //     options.success(_date);
                // }
            })
        }

// 超时 事件处理器
        function requestOnTimeout() {
            REQUEST.destroy()
        }

// 错误  事件处理器
        function requestOnError(err) {
            console.log('err: ', err)
        }

// 创建 http 连接
        const REQUEST = HTTP.request(POST_OPTIONS, requestOnResponse)

// 添加事件监听
        REQUEST.on('error', requestOnError)
        REQUEST.on('timeout', requestOnTimeout)

// 设置超时
        REQUEST.setTimeout(6000)

// 通过连接发送数据
        REQUEST.write(paramsStr, 'utf8')
        REQUEST.end()
    })
}
export const saveI18n = async (context: any, isDesign = false) => {
    const AWSReleasePath = process.env.AWSReleasePath ? process.env.AWSReleasePath : context.AWSDevParams.AWSReleasePath;
    const AWSPortalUrl = process.env.AWSPortalUrl ? process.env.AWSPortalUrl : context.AWSDevParams.AWSPortalUrl;
    const {
        i18n: {
            templatePath,
            i18nFileName,
            appId:pAppId,
            designTemplatePath,
            designI18NFileName,
            designAppId,
            keySpace,
        }
    } = context.AWSDevParams
    let jsonTemplate = {};
    for (const i of i18nSet) {
        jsonTemplate[i] = `<I18N#${i}>`
    }
    const templateFilePath = AWSReleasePath + (isDesign ? designTemplatePath : templatePath);
    const resI18nFileName = isDesign ? designI18NFileName : i18nFileName;
    const appId = context.AWSDevParams.appId == null ? (isDesign ? designAppId : pAppId) : context.AWSDevParams.appId;
    // const appId = "com.actionsoft.apps.saas100";
    let wirteJSONCode = "";
    if (keySpace != null && keySpace != "") {
        if (fs.existsSync(templateFilePath)) {
            const baseJsonTemplateStr = fs.readFileSync(templateFilePath, "utf8");
            try {
                const baseJsonTemplate = JSON.parse(baseJsonTemplateStr);
                baseJsonTemplate[keySpace] = jsonTemplate;
                wirteJSONCode = JSON.stringify(baseJsonTemplate, undefined, 2);
            } catch (e) {
                console.error("平台模板文件JSON格式损坏，请手动修复：" + templateFilePath)
            }
        } else {
            jsonTemplate = {
                [keySpace]: jsonTemplate
            };
        }
    }
    if ("" == wirteJSONCode) {
        wirteJSONCode = JSON.stringify(jsonTemplate, undefined, 2)
    }
    writeFile(templateFilePath, wirteJSONCode);
    const r: any = await httpRequestPromise({
        url: AWSPortalUrl,
        path: "r/jd",
        data: {
            userid: context.AWSDevParams.devUserInfo.userid,
            pwd: context.AWSDevParams.devUserInfo.pwd,
            lang: "cn",
            cmd: "CONSOLE_ADMIN_LOGIN",
            vueDeviceType: "pc",
        }
    });
    const sid = r.data.sid;
    const r2 = await httpRequestPromise({
        url: AWSPortalUrl,
        path: "r/jd",
        data: {
            cmd: "com.actionsoft.apps.addons.translate_create_app_i18n_file",
            sid,
            appId,
            fileName: resI18nFileName.replace(".xml", ""),
        }
    });
    const postData = {
        data: {
            keys: [] as string[],
            cn: [] as string[],
            en: [] as string[],
            big5: [] as string[],
        },
        remove: [],
        repeatData: []
    };
    let count = 0;
    for (const i of i18nSet) {
        console.log(i);
        postData.data.keys.push(i);
        postData.data.cn.push("");
        postData.data.en.push("");
        postData.data.big5.push("");
        count++;
    }
    console.log("共" + count + "个")
    for (const k in kinds) {
        console.log(k, kinds[k])
    }
    let wushangcount = 0;
    for (const k in wushangkinds) {
        console.log(k, wushangkinds[k])
        wushangcount++;
    }
    console.log("共无上" + wushangcount + "个")
    const r3: any = await httpRequestPromise({
        url: AWSPortalUrl,
        path: "r/jd",
        data: {
            cmd: "com.actionsoft.apps.addons.translate_save_i18n_datas",
            sid,
            appId,
            notUpdate: true,
            fileName: resI18nFileName.replace(".xml", "") + ".xml",
            datas: escape(JSON.stringify(postData)),
        }
    });
    if (r3.result == "ok") {
        console.log("保存成功")
    }
    console.log("结束")
}
